package com.sgb.kjwl.view.ui.adapter.machine;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.fondesa.recyclerviewdivider.DividerDecoration;
import com.sgb.kjwl.BR;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ItemAskLeaseBinding;
import com.sgb.kjwl.databinding.ItemCarHallSubVideoBinding;
import com.sgb.kjwl.databinding.ItemLeaseHallVideoBinding;
import com.sgb.kjwl.model.entity.lease.AskLeaseSheBeiEntity;
import com.sgb.knowledgeshare.utils.SharePermissionUtils;
import com.swgk.core.base.model.entity.VideoBean;
import com.sgb.kjwl.model.entity.transport.SingleItemConstant;
import com.sgb.knowledgeshare.view.activity.HomeShareActivity;
import com.sgb.knowledgeshare.view.activity.PlayListActivity;
import com.swgk.core.util.DateUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class AskLeaseAndVideoAdapter extends BaseMultiItemQuickAdapter<AskLeaseSheBeiEntity, BaseViewHolder> {
    /**
     * Same as QuickAdapter#QuickAdapter(Context,int) but with
     * some initialization data.
     *
     * @param data A new list is created out of this one to avoid mutable list
     */
    public AskLeaseAndVideoAdapter(List<AskLeaseSheBeiEntity> data) {
        super(data);
        //普通列表类别
        addItemType(SingleItemConstant.TYPE_ONE, R.layout.item_ask_lease);
        //视频类别
        addItemType(SingleItemConstant.TYPE_TWO, R.layout.item_lease_hall_videos);
        //单个视频类别
        addItemType(SingleItemConstant.TYPE_THREE, R.layout.item_lease_hall_video);
    }

    @Override
    protected void convert(BaseViewHolder helper, AskLeaseSheBeiEntity item) {
        switch (item.getItemType()) {
            case SingleItemConstant.TYPE_ONE:
                initCarInfo(helper, item);
                break;
            case SingleItemConstant.TYPE_TWO:
                initVideoList(helper, item);
                break;
            case SingleItemConstant.TYPE_THREE:
                initSingleVideo(helper, item);
                break;
        }
    }

    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
        RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
        if (manager instanceof GridLayoutManager) {
            final GridLayoutManager gridManager = ((GridLayoutManager) manager);
            gridManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {

                @Override
                public int getSpanSize(int position) {
                    if (getItemViewType(position) == SingleItemConstant.TYPE_ONE) {
                        return 1;
                    } else {
                        return 2;
                    }

                }
            });
        }
    }

    /**
     * 基本信息
     */
    private void initCarInfo(BaseViewHolder helper, AskLeaseSheBeiEntity entity) {
        //设置dataBinding数据
        ItemAskLeaseBinding binding = DataBindingUtil.bind(helper.itemView);
        if (binding == null) return;
        if (null != entity) {
            //状态(1:报价中;3:报价结束;4:已完成)
            if (entity.getStatus() == 1) {
                binding.ivQuoteState.setImageResource(R.mipmap.price_ing);
            } else if (entity.getStatus() == 3) {
                binding.ivQuoteState.setImageResource(R.mipmap.price_end_gray);
            } else if (entity.getStatus() == 4) {
                binding.ivQuoteState.setImageResource(R.mipmap.price_finish_fail);
            }

            //设置期望租金
            try {
                binding.tvTitle.setText(entity.getRentalTitle());
                if ("1".equals(entity.getNegotiable()) || Double.parseDouble(entity.getRentalPrice()) < 0) {
                    binding.tvSalary.setText("面议");
                } else {
                    binding.tvSalary.setText(entity.getRentalPrice() + "元/" + entity.getRentalDurationUnit());
                }
            } catch (Exception ex) {
                binding.tvSalary.setText("面议");
            }

            //设置租赁时长
            try {
                if (TextUtils.isEmpty(entity.getRentalDuration()) || Double.parseDouble(entity.getRentalDuration()) <= 0) {
                    binding.tvLeaseTime.setText("面议");
                } else {
                    binding.tvLeaseTime.setText(entity.getRentalDuration() + entity.getRentalDurationUnit());
                }
                //发布时间
                binding.tvLeasePublicTime.setText(DateUtils.stampToDay(entity.getUpdateTime()));
//                binding.tvEndTime.setText(DateUtils.stampToDate(entity.getEndTime()));
            } catch (Exception ex) {
            }

            /****************************因接口返回数据字段不一致,需要兼容********************************/

            if(!TextUtils.isEmpty(entity.getTaskAddr())){
                binding.tvLeaseAddr.setText(entity.getTaskAddr());
            }else{
                if (!TextUtils.isEmpty(entity.getLocation())) {
                    binding.tvLeaseAddr.setText(entity.getLocation().replace("/", ""));
                } else {
                    binding.tvLeaseAddr.setText(entity.getProvinceName() + entity.getCityName() + entity.getAreaName());
                }
            }

            try {
                binding.tvNumLabel.setText("租赁数量");
                if (!TextUtils.isEmpty(entity.getRentalCount()) && !TextUtils.isEmpty(entity.getRentalUnit())) {
                    binding.tvNum.setText(entity.getRentalCount() + entity.getRentalUnit());
                } else if (!TextUtils.isEmpty(entity.getRentalCount()) && !TextUtils.isEmpty(entity.getRentalCountUnit())) {
                    binding.tvNum.setText(entity.getRentalCount() + entity.getRentalCountUnit());
                } else if (!TextUtils.isEmpty(entity.getRentalCount())) {
                    binding.tvNum.setText(entity.getRentalCount());
                } else if (!TextUtils.isEmpty(entity.getNumOrArea())) {
                    binding.tvNum.setText(entity.getNumOrArea());
                }
            } catch (Exception e) {
            }

            //设置房产,土地,工厂租赁面积
            if ("4".equals(entity.getType()) || "5".equals(entity.getType()) || "6".equals(entity.getType())) {//土地求租
                binding.tvNumLabel.setText("租赁面积");
                if (!TextUtils.isEmpty(entity.getRentalArea())) {
                    binding.tvNum.setText(entity.getRentalArea() + " ㎡");
                }

            }

        }

    }


    /**
     * 设置视频信息
     */
    private void initVideoList(BaseViewHolder helper, AskLeaseSheBeiEntity entity) {
        RecyclerView recyclerView = helper.getView(R.id.rv_item_vehicle_hall_videos);
        recyclerView.setPadding(mContext.getResources().getDimensionPixelOffset(R.dimen.dp10),
                mContext.getResources().getDimensionPixelOffset(R.dimen.dp10),
                mContext.getResources().getDimensionPixelOffset(R.dimen.dp10),
                mContext.getResources().getDimensionPixelOffset(R.dimen.dp10));
        List<VideoBean> videoBeanList = new ArrayList<>();
        videoBeanList.addAll(entity.getVideoProDict());
        if (videoBeanList.size() >= 5) {
            VideoBean v = new VideoBean();
            v.setType("查看更多视频");
            videoBeanList.add(v);
        }
        CarsHallVideoAdapter adapter = new CarsHallVideoAdapter(videoBeanList);
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext, RecyclerView.HORIZONTAL, false));
        if (recyclerView.getItemDecorationCount() == 0) {
            DividerDecoration.builder(mContext)
                    .color(Color.TRANSPARENT)
                    .size(10, TypedValue.COMPLEX_UNIT_DIP)
                    .build()
                    .addTo(recyclerView);
        }
        adapter.bindToRecyclerView(recyclerView);
        adapter.setOnItemClickListener((adapter1, view, position) -> {
            if (adapter.getData().get(position).isCheckMoreVideos()) {
                SharePermissionUtils.getPermissionTwo((Activity) mContext,1);
            } else {
                //视频播放
                Intent intent = new Intent(mContext, PlayListActivity.class);
                intent.putExtra(PlayListActivity.VIDEOLISTBEAN, (Serializable) entity.getVideoProDict());
                intent.putExtra(PlayListActivity.PSO, position);
                intent.putExtra(PlayListActivity.VIDEOTYPE, "home_lease");
                mContext.startActivity(intent);
            }
        });
    }

    /**
     * 设置单个视频信息
     */
    private void initSingleVideo(BaseViewHolder helper, AskLeaseSheBeiEntity entity) {
        //设置dataBinding数据
        ItemLeaseHallVideoBinding binding = DataBindingUtil.bind(helper.itemView);
        if (binding == null) return;
        if (entity.getVideoProDict() != null && !entity.getVideoProDict().isEmpty()) {
            binding.setVariable(BR.viewModel, entity.getVideoProDict().get(0));
            binding.executePendingBindings();
        }
    }


    /**
     * 视频适配器
     */
    private static class CarsHallVideoAdapter extends BaseQuickAdapter<VideoBean, BaseViewHolder> {

        public CarsHallVideoAdapter(@Nullable List<VideoBean> data) {
            super(R.layout.item_car_hall_sub_video, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, VideoBean entity) {

            if (entity.isCheckMoreVideos()) {
                ((ImageView) helper.getView(R.id.tag_cuxiao)).setImageDrawable(mContext.getResources().getDrawable(R.drawable.check_more_video));
                ((ImageView) helper.getView(R.id.iv_item_car_hall_video)).setImageDrawable(mContext.getResources().getDrawable(R.drawable.gray_radius_bkg));
                (helper.getView(R.id.more_video_text)).setVisibility(View.VISIBLE);
                (helper.getView(R.id.title_view)).setVisibility(View.GONE);
            } else {
                //设置dataBinding数据
                (helper.getView(R.id.title_view)).setVisibility(View.VISIBLE);
                (helper.getView(R.id.more_video_text)).setVisibility(View.GONE);
                ((ImageView) helper.getView(R.id.tag_cuxiao)).setImageDrawable(mContext.getResources().getDrawable(R.mipmap.icn_video_play));
                ItemCarHallSubVideoBinding binding = DataBindingUtil.bind(helper.itemView);
                if (binding == null) return;
                binding.setVariable(BR.viewModel, entity);
                binding.executePendingBindings();
            }

        }
    }
}
